package com.frame.auth.security.service;

import com.frame.auth.mvc.dao.mapper.CloudAuthClientMapper;
import com.frame.auth.mvc.dao.mapper.CloudAuthClientResourceMapper;
import com.frame.auth.mvc.dao.pojo.CloudAuthClient;
import com.frame.auth.mvc.dao.pojo.CloudAuthClientExample;
import com.frame.auth.mvc.dao.pojo.CloudAuthClientResource;
import com.frame.auth.mvc.dao.pojo.CloudAuthClientResourceExample;
import com.frame.auth.security.config.PasswordConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @auther zhangwj
 * @date 2021/3/11 上午9:53
 */
@Configuration
public class AuthClientDetailsService implements ClientDetailsService {

    @Resource
    private CloudAuthClientMapper cloudAuthClientMapper;

    @Resource
    private CloudAuthClientResourceMapper cloudAuthClientResourceMapper;

    @Resource
    private PasswordConfig passwordConfig;

    @Override
    public ClientDetails loadClientByClientId(String appKey) throws ClientRegistrationException {
        CloudAuthClientExample cloudAuthClientExample = new CloudAuthClientExample();
        CloudAuthClientExample.Criteria cloudAuthClientCriteria = cloudAuthClientExample.createCriteria();
        cloudAuthClientCriteria.andAppKeyEqualTo(appKey);
        List<CloudAuthClient> cloudAuthClientList = cloudAuthClientMapper.selectByExample(cloudAuthClientExample);
        if (null == cloudAuthClientList || cloudAuthClientList.size() != 1) {
            return new CloudAuthClient();
        }
        CloudAuthClient cloudAuthClient = cloudAuthClientList.get(0);
        Set<String> resourceIds = new HashSet<>();
        CloudAuthClientResourceExample cloudAuthClientResourceExample = new CloudAuthClientResourceExample();
        CloudAuthClientResourceExample.Criteria cloudAuthClientResourceCriteria = cloudAuthClientResourceExample.createCriteria();
        cloudAuthClientResourceCriteria.andAppKeyEqualTo(appKey);
        List<CloudAuthClientResource> cloudAuthClientResourceList = cloudAuthClientResourceMapper.selectByExample(cloudAuthClientResourceExample);
        if (null != cloudAuthClientResourceList && !cloudAuthClientResourceList.isEmpty()) {
            cloudAuthClientResourceList.forEach(cloudAuthClientResource -> resourceIds.add(cloudAuthClientResource.getResourceId()));
        }
        cloudAuthClient.setResourceIds(resourceIds);
        cloudAuthClient.setAppSecret(passwordConfig.getPasswordEncoder().encode(cloudAuthClient.getAppSecret()));
        return cloudAuthClient;
    }


}



